import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter ,constantRoutes,allAsyncRoutes,anyRoutes} from '@/router'

// 过滤异步路由函数
import {cloneDeep} from 'lodash'
function filterAsyncRoutes(allAsyncRoutes,routesName){
  //深拷贝
  const cloneAllAsyncRoutes=cloneDeep(allAsyncRoutes)
  //过滤
  const result = cloneAllAsyncRoutes.filter((element)=>{
      if(routesName.indexOf(element.name)!==-1){
        if(element.children&&element.children.length>0){
          element.children=filterAsyncRoutes(element.children,routesName)
        }
        return true
      }
  })
  return result
}

// const getDefaultState = () => {
//   return {
//     token: getToken(),
//     name: '',
//     avatar: ''
//   }
// }

// const state = getDefaultState()

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  buttons:[],
  roles:[],
  routes:[]
}

const mutations = {
  // RESET_STATE: (state) => {
  //   Object.assign(state, getDefaultState())
  // },
  RESET_STATE: (state) => {
    state.token= getToken(),
    state.name= '',
    state.avatar= ''
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // SET_NAME: (state, name) => {
  //   state.name = name
  // },
  // SET_AVATAR: (state, avatar) => {
  //   state.avatar = avatar
  // }
  SET_USERINFO:(state,userInfo)=>{
    state.name = userInfo.name
    state.avatar = userInfo.avatar
    state.buttons = userInfo.buttons
    state.roles = userInfo.roles
  },
  SET_ROUTES:(state,asyncRoutes)=>{
    state.routes=constantRoutes.concat(asyncRoutes,anyRoutes)
    //添加到路由规则中
    router.addRoutes([...asyncRoutes,anyRoutes])
  }
}

const actions = {
  // user login
  // login({ commit }, userInfo) {
  //   const { username, password } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({ username: username.trim(), password: password }).then(response => {
  //       const { data } = response
  //       commit('SET_TOKEN', data.token)
  //       setToken(data.token)
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  async login({commit},userInfo){
    const {username,password} =userInfo
    try {
      const result =await login({ username: username.trim(), password: password })
      const {data} =result 
      commit('SET_TOKEN', data.token)
      setToken(data.token)
    } catch (error) {
      return Promise.reject(error)
    }
  },

  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  async getInfo({ commit, state }){
    try {
      const result =await getInfo(state.token)
      const {data} =result
      if (!data) {
        return Promise.reject('Verification failed, please Login again.')
      }
      commit('SET_USERINFO', data)
      commit('SET_ROUTES',filterAsyncRoutes(allAsyncRoutes,data.routes))
    } catch (error) {
      return Promise.reject(error.message)
    }
    
  },

  // user logout
  // logout({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       removeToken() // must remove  token  first
  //       resetRouter()
  //       commit('RESET_STATE')
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  async logout({ commit, state }){
    try {
      const result=await logout(state.token)
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
    } catch (error) {
      return Promise.reject(error)
    }
    
  },

  // remove token
  // resetToken({ commit }) {
  //   return new Promise(resolve => {
  //     removeToken() // must remove  token  first
  //     commit('RESET_STATE')
  //     resolve()
  //   })
  // },
  async resetToken({ commit }){
    removeToken() // must remove  token  first
    commit('RESET_STATE')
  }
  
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

